//@login register
const express = require("express");
const router = express.Router();
const bcrypt = require("bcrypt");
const jwt = require('jsonwebtoken');
//const gravatar = require("gravatar");
const keys = require("../../config/keys");

const User = require("../../models/User");
const passport = require("passport");


// $route GET api/users/test
// @desc 返回请求的JSON数据
// @access public
//router.get("/test", (req, res) => {
//  res.json({ mgs: "login works" })
//})

//$route POST api/users/register
//@desc 返回请求的JSON数据
//@access public
router.post("/register", (req, res) => {
  //console.log(res.boy);

  //查询数据库中是否拥有邮箱
  User.findOne({ email: req.body.email }).then((user) => {
    if (user) {
      return res.status(400).json('邮箱已被注册' );
    } else {
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar: avatar,
        password: req.body.password,
        identity:req.body.identity,
      })
      //加密

      bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser.save().then(
            user => res.json(user)).catch(
              err => console.log(err));
          // Store hash in your password DB.
        });
      });

    }
  })
})

// $route GET api/users/login
// @desc 返回token jwt passport
// @access public

router.post("login", (req, res) => {
  const rmail = req.body.email;
  const password = req.body.password;
  //查询数据库
  User.findOne({ email: email }).then(user => {
    if (!user) {
      return res.status().json('用户不存在');
    } else {
      //密码匹配
      // Load hash from your password DB.
      bcrypt.compare(password, user.password).then(isMatch => {
        if (isMatch) {
          //jwt.sign("规则","加密名字","过期时间","箭头函数")
          const rule = { 
            id: user.id,
            name: user.name,
            avatar:user.avatar,
            identity:user.identity
            };

          jwt.sign(rule,keys.secretOrKey,{expiresIn:3600},(err,token)=>{
            if(err) throw err;
            res.json({
              success:true,
              token:'Bearer '+token,
            })
          })
          //res.json({ msg: 'success' });
        } else {
          return res.status(400).json('密码错误！');
        }
      })
    }
  }).catch()
})

// $route Get api/users/current
// @desc return current user
// @access Private
router.get("/current",passport.authenticate("jwt",{session:false}),(req,res)=>{
  //res.json({msg:"success"});
  //res.json({msg:"req.user"});
  res.json({
    id:req.user.id,
    name:req.user.name,
    email:req.user.email,
    identity:req.user.identity
  });
});




module.exports = router;

